package com.base;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import org.apache.struts2.ServletActionContext;

import com.domain.Function;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

public class BaseAction<T> extends ActionSupport implements ModelDriven<T> {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected T model;						//声明模型驱动,将变量声明为protected 继承的子类才能使用.
	@Override
	public T getModel() {
		return model;
	}
	
	public BaseAction(){					//通过构造获得实体类型
		ParameterizedType genericSuperclass = (ParameterizedType)this.getClass().getGenericSuperclass();		//获得父类类型
		Type[] actualTypeArguments = genericSuperclass.getActualTypeArguments();								//获得泛型参数类型
		//model = (T) actualTypeArguments[0];	
		//实体类型
		Class<T> domainClass = (Class<T>) actualTypeArguments[0];
		try {
			model = domainClass.newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}//获得实体类型
	}
	public void writeList2json(List<T> functionList, String[] strings) {
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.setExcludes(strings);
		JSONArray jsonObject = JSONArray.fromObject(functionList, jsonConfig);
		String json = jsonObject.toString();
		//System.out.println(json);
		// 将json数据通过输出流写到客户端
		ServletActionContext.getResponse().setContentType("text/json;charset=UTF-8");
		try {
			ServletActionContext.getResponse().getWriter().print(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
